package common

import "github.com/micro/go-micro/v2/config"
import "github.com/jinzhu/gorm"
import _ "github.com/jinzhu/gorm/dialects/mysql"
import log "github.com/micro/go-micro/v2/logger"

//创建结构体
type MysqlConfig struct {
	Host string `json:"host"`
	User string `json:"user"`
	Pwd string `json:"pwd"`
	Database string `json:"database"`
	Port int64 `json:"port"`
}

//获取mysql的配置
func MysqlConfigFromConsul(config config.Config,path ...string) *MysqlConfig   {
	mysqlConfig := &MysqlConfig{}
	config.Get(path...).Scan(mysqlConfig)
	return mysqlConfig
}

//注册mysql
func RegMysql(mysqlInfo *MysqlConfig) *gorm.DB {
	var url = mysqlInfo.User+":"+mysqlInfo.Pwd+"@("+ mysqlInfo.Host+":3306" +")/"+
		mysqlInfo.Database+"?charset=utf8&parseTime=True&loc=Local"
	log.Info("mysql配置url",url)
	db,err := gorm.Open("mysql", url)
	if err != nil {
		log.Error(err)
	}
	//defer db.Close()
	db.SingularTable(true)
	return db
}

//注册mysql 制定数据库名称
func RegMysqlWithDatabase(mysqlInfo *MysqlConfig, dataBase string) *gorm.DB {
	db,err := gorm.Open("mysql",mysqlInfo.User+":"+mysqlInfo.Pwd+"@/"+
		dataBase+"?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		log.Error(err)
	}
	//defer db.Close()
	db.SingularTable(true)
	return db
}


